package controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pojo.*;
import service.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/dev")
public class Dev_userController {
    //@Autowired
    @Resource
    private App_infoService appInfoService;
    @Resource
    private Dev_userService devUserService;
    @Resource
    private Data_dictionaryService dataDictionaryService;
    @Resource
    private App_categoryService appCategoryService;
    @Resource
    private App_versionService appVersionService;
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "devlogin";
    }

    @RequestMapping("/login")
    public String getUser(@RequestParam String devCode, @RequestParam String devPassword, HttpSession session) {
        if (devUserService.devCode(devCode) == 0) {
            throw new RuntimeException("用户名不存在！");
        } else if (devUserService.devPassword(devPassword) == 0) {
            throw new RuntimeException("密码输入错误！");
        } else {
            Dev_user user = devUserService.getUser(devCode, devPassword);
            session.setAttribute("devUserSession", user);
        }
        return "/developer/main";
    }

    //注销
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/index.jsp";
    }

    //跳转到手游审核页面
    @RequestMapping("/flatform/app/list")
    public String toAppList(Model model, @RequestParam(required = false) String querySoftwareName, @RequestParam(required = false) String queryStatus, @RequestParam(required = false) String queryFlatformId, @RequestParam(required = false) String queryCategoryLevel1,
                            @RequestParam(required = false) String queryCategoryLevel2, @RequestParam(required = false) String queryCategoryLevel3, @RequestParam(defaultValue = "1") String pageIndex) {
        List<App_info> list = null;
        if (queryStatus == null || queryStatus == "") {
            queryStatus = "0";
        }
        if (queryFlatformId == null || queryFlatformId == "") {
            queryFlatformId = "0";
        }
        if (queryCategoryLevel1 == null || queryCategoryLevel1 == "") {
            queryCategoryLevel1 = "0";
        }
        if (queryCategoryLevel2 == null || queryCategoryLevel2 == "") {
            queryCategoryLevel2 = "0";
        }
        if (queryCategoryLevel3 == null || queryCategoryLevel3 == "") {
            queryCategoryLevel3 = "0";
        }
        Page page = new Page();
        page.setCurrentPageNo(Integer.parseInt(pageIndex));//当前页面
        page.setPageSize(5);        //页面大小
        devUserService.fy(page, querySoftwareName, Integer.parseInt(queryStatus), Integer.parseInt(queryFlatformId), Integer.parseInt(queryCategoryLevel1), Integer.parseInt(queryCategoryLevel2),
                Integer.parseInt(queryCategoryLevel3));
        list = page.getList();
        List<Data_dictionary> list2 = dataDictionaryService.getvalueNameBytypeCode();//所有平台
        List<Data_dictionary> status = dataDictionaryService.getStatus();//所有状态
        model.addAttribute("categoryLevel1List", appCategoryService.getByParentId(1));
        model.addAttribute("categoryLevel2List", appCategoryService.getByParentId(2));
        model.addAttribute("categoryLevel3List", appCategoryService.getByParentId(3));
//        List<App_category> list3=appCategoryService.list();//查询一级分类
//        List<App_category> list4=appCategoryService.list2();//查询二级分类
//        List<App_category> list5=appCategoryService.list3();//查询二级分类
        model.addAttribute("statusList", status);
//        model.addAttribute("categoryLevel3List",list5);
//        model.addAttribute("categoryLevel2List",list4);
//        model.addAttribute("categoryLevel1List",list3);

        model.addAttribute("flatFormList", list2);
        model.addAttribute("pages", page);
        model.addAttribute("appInfoList", list);
        model.addAttribute("querySoftwareName", querySoftwareName);
        model.addAttribute("queryStatus", queryStatus);
        model.addAttribute("queryFlatformId", Integer.parseInt(queryFlatformId));
        model.addAttribute("queryCategoryLevel1", Integer.parseInt(queryCategoryLevel1));
        model.addAttribute("queryCategoryLevel2", Integer.parseInt(queryCategoryLevel2));
        model.addAttribute("queryCategoryLevel3", Integer.parseInt(queryCategoryLevel3));
//        model.addAttribute("currPage",currPage);
        return "developer/appinfolist";
    }

    @ResponseBody
    @RequestMapping(value = "/byPagrentId", produces = {"application/json;charset=utf-8"})
    public Object byPagrentId(@RequestParam(value = "pid") int pid) {
        List<App_category> list = appCategoryService.getByParentId(pid);
        return JSON.toJSONString(list);

    }

    /**
     * 跳转到新增版本
     */
    //@ResponseBody
    @RequestMapping("/flatform/app/appversionadd")
    public String toAdd(Model model,@RequestParam Integer id) {
        List<App_version> getListById = appVersionService.selectByAppId(id);
        model.addAttribute("appVersionList",getListById);
        model.addAttribute("appId",id);
        return "developer/appversionadd";
    }

    /**
     * 新增App基础信息
     */
    //@ResponseBody
    @RequestMapping("/flatform/app/appinfoadd")
    public String toAddInfo() {
        return "developer/appinfoadd";
    }

    @RequestMapping(value = "/ptjson", produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public Object ptjson() {
        List<Data_dictionary> list = dataDictionaryService.getvalueNameBytypeCode();
        return JSON.toJSONString(list);
    }

    @RequestMapping(value = "/apkname", produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public Object apkname(@RequestParam String APKName) {
        Map<String, Object> map = new HashMap<>();
        if (APKName == "" || APKName == null) {
            map.put("APKName", "empty");
        } else if (appInfoService.getApk(APKName) > 0) {
            map.put("APKName", "exist");
        } else {
            map.put("APKName", "noexist");
        }
        return JSON.toJSONString(map);
    }



    /**
     * 新增手游信息
     *
     * @return
     */
    @RequestMapping(value = "/appinfoaddsave")
    public String add(App_info app_info, HttpSession session, HttpServletRequest request, @RequestParam(value = "a_logoPicPath") MultipartFile a_logoPicPath) {
        String logoPic = null;
        String logoPic2=null;
        String errorInfo = null;
        String path=null;
        String fileName=null;
        //String flag=true;
        if (!a_logoPicPath.isEmpty()) {
            path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");//文件路径
            String originalFile = a_logoPicPath.getOriginalFilename();//原文件名
            String prefix = FilenameUtils.getExtension(originalFile);//原文件后缀
            int fileSize = 500000;//文件大小
            if (a_logoPicPath.getSize() > fileSize) {
                request.setAttribute("uploadFileError", "* 上传大小不得超过500kb");
                return "developer/appinfoadd";
            } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
                //判断图片格式是否正确
                fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                File targetFile = new File(path);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                //保存
                try {
                    a_logoPicPath.transferTo(new File(targetFile, fileName));
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", "*上传失败!");
                    return "developer/appinfoadd";
                }
                //logoPic = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                logoPic=session.getServletContext().getContextPath()+"/statics/uploadfiles/"+fileName;
                logoPic2=path+File.separator+fileName;

            } else {
                request.setAttribute("uploadFileError", "*上传图片格式不正确");
                return "developer/appinfoadd";
            }
        } else {
            request.setAttribute("e", "请选择要上传的文件");
            return "developer/appinfoadd";
        }
//            App_info appInfo = (App_info) session.getAttribute("appSession");
        app_info.setLogoLocPath(logoPic2);
        app_info.setLogoPicPath(logoPic);

        if (appInfoService.add(app_info) > 0) {
            return "redirect:/dev/flatform/app/list";
        }
        return "/dev/appinfoaddsave";
    }

    /**
     * 跳转到修改App基础信息
     */
    //@ResponseBody
    @RequestMapping("/flatform/app/appinfomodify")
    public String toUpdate(Model model, int id) {
        App_info getListById = appInfoService.getListById(id);
        model.addAttribute("appInfo",getListById);
        return "/developer/appinfomodify";
    }
    /**
     * 修改手游信息
     *
     * @return
     */
    @RequestMapping(value = "/appupdate")
    public String update(App_info app_info, HttpSession session, HttpServletRequest request, @RequestParam(value = "attach") MultipartFile a_logoPicPath) {
        String logoPic = null;
        String logoPic2=null;
        String errorInfo = null;
        String path=null;
        String fileName=null;
        //String flag=true;
        if (!a_logoPicPath.isEmpty()) {
            path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");//文件路径
            String originalFile = a_logoPicPath.getOriginalFilename();//原文件名
            String prefix = FilenameUtils.getExtension(originalFile);//原文件后缀
            int fileSize = 500000;//文件大小
            if (a_logoPicPath.getSize() > fileSize) {
                request.setAttribute("uploadFileError", "* 上传大小不得超过500kb");
                return "redirect:/dev/flatform/app/appinfomodify";
            } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
                //判断图片格式是否正确
                fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                File targetFile = new File(path);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                //保存
                try {
                    a_logoPicPath.transferTo(new File(targetFile, fileName));
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", "*上传失败!");
                    return "redirect:/dev/flatform/app/appinfomodify";
                }
                logoPic = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                logoPic=session.getServletContext().getContextPath()+"/statics/uploadfiles/"+fileName;
                logoPic2=path+"\\"+fileName;

            } else {
                request.setAttribute("uploadFileError", "*上传图片格式不正确");
                return "redirect:/dev/flatform/app/appinfomodify";
            }
        }
//            App_info appInfo = (App_info) session.getAttribute("appSession");
//        logoPic=session.getServletContext().getContextPath()+"/statics/uploadfiles/"+fileName;
//        logoPic2=path+"\\"+fileName;
//        app_info.setLogoLocPath(logoPic2);
//        app_info.setLogoPicPath(logoPic);
        app_info.setLogoLocPath(logoPic2);
        app_info.setLogoPicPath(logoPic);
        if (appInfoService.upd(app_info) > 0) {
            return "redirect:/dev/flatform/app/list";
        }
        return "developer/appinfolist";
    }

    /**
     * 删除图片
     */
    @RequestMapping(value = "/delfile", produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public Object delfile(@RequestParam Integer id,@RequestParam String flag, HttpServletRequest request) {
        Map<String,String> map=new HashMap<String,String>();
        App_info appInfo=appInfoService.getID(id);
        File file=new File(appInfo.getLogoLocPath());
        if (file.delete()) {
            map.put("result","success");
        }else{
            map.put("result","failed");
        }
        return JSON.toJSONString(map);
    }

    /**
     * 删除文件
     */
    @RequestMapping("/wenjian")
    @ResponseBody
    public Object delwj(@RequestParam Integer id,@RequestParam String flag) {
        Map<String,String> map=new HashMap<String,String>();
//        App_info appInfo=appInfoService.getID(id);
        App_version version=appVersionService.selectById(id);
        File file=new File(version.getApkLocPath());
        if (file.delete()) {
            map.put("result","success");
        }else{
            map.put("result","failed");
        }
        return JSON.toJSONString(map);
    }
    /**
     * 删除App基础信息
     */
    @RequestMapping(value = "/flatform/app/del", produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public Object del(@RequestParam Integer id,HttpServletRequest request) {
        Map<String,String> map=new HashMap<String,String>();
        List<App_version> list=appVersionService.selectByAppId(id);//根据ID查询版本信息
        App_info list2=appInfoService.getID(id);//根据ID查询图片
        File file=new File(list2.getLogoLocPath());
        if (list.size()!=0){
            int result = appVersionService.del(id);
            if (result>0){
                if (file.delete()) {
                    if (appInfoService.del(id)>0) {
                        map.put("result","true");
                    }else{
                        map.put("result","false");
                    }
                }else{
                    map.put("result","false");
                }
            }else{
                map.put("result","false");
            }
        }
       appInfoService.del(id);
        map.put("result","true");
//        int num=appInfoService.del(id);
//        return JSON.toJSONString(num);
        return JSON.toJSONString(map);
    }

    /**
     * 新增App版本信息
     */
    @PostMapping("/flatform/app/addversionsave")
    public String addVersion(App_version appVersion, HttpSession session,
                             HttpServletRequest request,
                             @RequestParam(value = "attach" ,required = false) MultipartFile attach){
        //List<App_version> appVersionList=appVersionService.selectByAppId(id);
        String downloadLink=null;
        String apkLocPath=null;
        String apkFileName=null;
        if (!attach.isEmpty()){
            String path=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
            //logger.debug("服务器路径："+path);
            String oldFileName=attach.getOriginalFilename();
            //logger.debug("原文件名："+oldFileName);
            String prefix=FilenameUtils.getExtension(oldFileName);
            if (prefix.equalsIgnoreCase("apk")){
                String apkName=null;
                try {
                    App_info info=appInfoService.selectById(appVersion.getAppId());
                    apkName=info.getAPKName();
                    //logger.debug("apk文件名："+apkName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (apkName==null || "".equals(apkName)){
                    request.setAttribute("fileUploadError","APK名称不能为空！");
                    return "redirect:/dev/flatform/app/appversionadd?id="+appVersion.getAppId();
                }
                apkFileName=apkName+"-"+appVersion.getVersionNo()+".apk";
                File targetFile=new File(path,apkFileName);
                if (!targetFile.exists()){
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    request.setAttribute("fileUploadError","文件上传失败！");
                    return "redirect:/dev/flatform/app/appversionadd?id="+appVersion.getAppId();
                }
                downloadLink=request.getContextPath()+"/statics/uploadfiles/"+apkFileName;
                apkLocPath=path+File.separator+apkFileName;
            }else {
                request.setAttribute("fileUploadError","文件格式不正确！");
                return "redirect:/dev/flatform/app/appversionadd?id="+appVersion.getAppId();
            }
        }
        appVersion.setApkFileName(apkFileName);
        appVersion.setApkLocPath(apkLocPath);
        appVersion.setDownloadLink(downloadLink);
        appVersion.setCreatedBy(((Dev_user)session.getAttribute("devUserSession")).getId());
        if (appVersionService.addVersion(appVersion)>0){
            appInfoService.updateVersionId(appVersion.getAppId(),appVersion.getId());
            return "redirect:/dev/flatform/app/list";
        }else {
            request.setAttribute("fileUploadError","新增版本信息失败！");
            return "redirect:/dev/flatform/app/appversionadd?id="+appVersion.getAppId();
        }

    }

    /**
     * 跳转到修改页面
     * @param vid
     * @param aid
     * @param model
     * @return
     */
    @RequestMapping("/toModify")
    public String toModify(@RequestParam Integer vid,@RequestParam Integer aid,Model model){
        List<App_version> appVersionList=appVersionService.selectByAppId(aid);
        App_version appVersion=appVersionService.selectById(vid);
        model.addAttribute("appVersionList",appVersionList);
        model.addAttribute("appVersion",appVersion);
        return "developer/appversionmodify";
    }

    /**
     * 修改版本信息
     * @param appVersion
     * @param session
     * @param request
     * @param attach
     * @return
     */
    @RequestMapping("/flatform/app/appversionmodifysave")
    public String modifyVersion(App_version appVersion,HttpSession session,HttpServletRequest request,
                                @RequestParam(value = "attach",required = false) MultipartFile attach){
        String downloadLink=null;
        String apkLocPath=null;
        String apkFileName=null;
        if (!attach.isEmpty()){
            String path=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
            //logger.debug("服务器路径："+path);
            String oldFileName=attach.getOriginalFilename();
            //logger.debug("原文件名："+oldFileName);
            String prefix=FilenameUtils.getExtension(oldFileName);
            if (prefix.equalsIgnoreCase("apk")){
                String apkName=null;
                try {
                    apkName=appInfoService.selectById(appVersion.getAppId()).getAPKName();
                    //logger.debug("apk文件名："+apkName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (apkName==null || "".equals(apkName)){
                    request.setAttribute("fileUploadError","APK名称不能为空！");
                    return "forward:/version/toModify?vid="+appVersion.getId()+"&aid="+appVersion.getAppId();
                }
                apkFileName=apkName+"-"+appVersion.getVersionNo()+".apk";
                File targetFile=new File(path,apkFileName);
                if (!targetFile.exists()){
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    request.setAttribute("fileUploadError","文件上传失败！");
                    //return "forward:/version/toModify?vid="+appVersion.getId()+"&aid="+appVersion.getAppId();
                    return "/developer/appversionadd";
                }
                downloadLink=request.getContextPath()+"/statics/uploadfiles/"+apkFileName;
                apkLocPath=path+File.separator+apkFileName;
            }else {
                request.setAttribute("fileUploadError","文件格式不正确！");
                //return "forward:/version/toModify?vid="+appVersion.getId()+"&aid="+appVersion.getAppId();
                return "/developer/appversionadd";
            }
        }
        appVersion.setApkFileName(apkFileName);
        appVersion.setApkLocPath(apkLocPath);
        appVersion.setDownloadLink(downloadLink);
        Dev_user devUser =(Dev_user) session.getAttribute("devUserSession");
        appVersion.setModifyBy(devUser.getId());
        if (appVersionService.updateVersion(appVersion)>0){
            return "redirect:/dev/flatform/app/list";
        }else {
            request.setAttribute("fileUploadError","修改版本信息失败！");
            //return "forward:/version/toModify?vid="+appVersion.getId()+"&aid="+appVersion.getAppId();
            return "/developer/appversionadd";
        }
    }

    /**
     * 跳转到详情页面
     */
    @RequestMapping("/flatform/app/appview")
    public String toXianG(@RequestParam Integer id,Model model){
        List<App_version> appVersionList=appVersionService.selectByAppId(id);
        App_info getListById = appInfoService.getListById(id);
        model.addAttribute("appVersionList",appVersionList);
        model.addAttribute("appInfo",getListById);
        return "developer/appinfoview";
    }
    /**
     * 上架
     */
    @RequestMapping("/{pid}/sale")
    @ResponseBody
    public Object sale(@PathVariable Integer pid){
        Map<String,String> map=new HashMap<String,String>();
        App_info appInfo=appInfoService.getsjById(pid);
        map.put("errorCode","0");
        if (appInfo.getStatus()==2||appInfo.getStatus()==5){
            if(appInfoService.UpdateById(pid,4)>0){
                map.put("resultMsg","success");
            }else{
                map.put("resultMsg","failed");
            }
        }else{
            if(appInfoService.UpdateById(pid,5)>0){
                map.put("resultMsg","success");
            }else{
                map.put("resultMsg","failed");
            }
        }
        return JSON.toJSONString(map);
    }
}
